package com.javatest.springboot3minio.controller;

import com.javatest.springboot3minio.service.AttachmentManageService;
import javax.validation.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created with IntelliJ IDEA. Description:
 *
 * @author liuzi
 * @since 2024/1/10 11:25
 */
@Validated
@Controller
public class FileUploadController {
  private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);
  private static final String FILE_UPLOAD_SUCCESS = "文件上传成功";
  private static final String FILE_UPLOAD_FAIL = "文件上传失败, 请重试";
  private AttachmentManageService attachmentManageService;

  @Autowired
  public void setAttachmentManageService(AttachmentManageService attachmentManageService) {
    this.attachmentManageService = attachmentManageService;
  }

  @ResponseBody
  @PostMapping("/upload")
  public String uploadFile(
      @RequestParam("projectId") @NotBlank(message = "projectId不能为空") String projectId,
      @RequestParam("attachmentType") @NotBlank(message = "attachmentType不能为空")
          String attachmentType,
      @RequestParam("file") MultipartFile file) {
    LOGGER.info("收到上传文件[{}]", file.getOriginalFilename());

    final boolean result =
        attachmentManageService.uploadAttachment(projectId, attachmentType, file);
    return result ? FILE_UPLOAD_SUCCESS : FILE_UPLOAD_FAIL;
  }
}
